package com.gitee.qdbp.jdbc.plugins.impl;

import java.util.Map;
import com.gitee.qdbp.jdbc.plugins.JdbcDataTypeResolver;
import com.gitee.qdbp.tools.utils.ConvertTools;
import com.gitee.qdbp.tools.utils.StringTools;

/**
 * JDBC数据类型转换: 将代码中写的数据类型转换为java.sql.Types中的数据类型
 *
 * @author zhaohuihua
 * @version 20210430
 */
public class SimpleJdbcDataTypeResolver implements JdbcDataTypeResolver {

    private final Map<String, ?> supportDefinePrecisionMaps;
    private final Map<String, ?> supportDefineScaleMaps;
    private final Map<String, ?> supportDefineLengthMaps;
    private final Map<String, ?> supportUnicodeMaps;

    public SimpleJdbcDataTypeResolver() {
        String precisions = "BIT|TINYINT|SMALLINT|INTEGER|BIGINT";
        String scales = "FLOAT|DOUBLE|REAL|NUMERIC|DECIMAL";
        String lengths = "CHAR|VARCHAR|LONGVARCHAR|NCHAR|NVARCHAR|LONGNVARCHAR";
        String unicodes = "NCHAR|NVARCHAR|LONGNVARCHAR|NCLOB";
        this.supportDefinePrecisionMaps = ConvertTools.toMap(StringTools.splits(precisions));
        this.supportDefineScaleMaps = ConvertTools.toMap(StringTools.splits(scales));
        this.supportDefineLengthMaps = ConvertTools.toMap(StringTools.splits(lengths));
        this.supportUnicodeMaps = ConvertTools.toMap(StringTools.splits(unicodes));
    }

    @Override
    public Integer parseDataType(String dataType) {
        return JdbcDataTypeCache.getJdbcType(dataType);
    }

    @Override
    public String getJdbcType(String dataType) {
        return dataType;
    }

    @Override
    public boolean supportDefinePrecision(String dataType) {
        String jdbcType = getJdbcType(dataType);
        return supportDefinePrecisionMaps.containsKey(jdbcType) || supportDefineScaleMaps.containsKey(jdbcType);
    }

    @Override
    public boolean supportDefineScale(String dataType) {
        String jdbcType = getJdbcType(dataType);
        return supportDefineScaleMaps.containsKey(jdbcType);
    }

    @Override
    public boolean supportDefineLength(String dataType) {
        String jdbcType = getJdbcType(dataType);
        return supportDefineLengthMaps.containsKey(jdbcType);
    }

    @Override
    public boolean supportUnicode(String dataType) {
        String jdbcType = getJdbcType(dataType);
        return supportUnicodeMaps.containsKey(jdbcType);
    }
}
